//
//  EvaluationTableViewController.m
//  何五路
//
//  Created by _ADY on 15/6/16.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "EvaluationTableViewController.h"
#import "TQStarRatingView.h"
#import "GoodsDetailsViewController.h"
NSString *const MJTableViewCellIdentifier = @"Cell";
static LoadingView *loading = nil;
#define picTag 1000000
#define xhTag 5000000
@interface EvaluationTableViewController ()

@end

@implementation EvaluationTableViewController
@synthesize allArray,productId,delegate,evaluationArray,_photos,_thumbs,msArray,xhArray;
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    ccsInt = 0;
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 设置文字
    [header setTitle:@"下拉，返回商品详情" forState:MJRefreshStateIdle];
    [header setTitle:@"松开，返回商品详情" forState:MJRefreshStatePulling];
    [header setTitle:@"" forState:MJRefreshStateRefreshing];
    // 设置字体
//    header.stateLabel.font = [UIFont systemFontOfSize:15];
//    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    
    // 设置颜色
//    header.stateLabel.textColor = [UIColor redColor];
//    header.lastUpdatedTimeLabel.textColor = [UIColor blueColor];
    header.lastUpdatedTimeLabel.hidden = YES;
    // 马上进入刷新状态
//    [header beginRefreshing];
    
    // 设置刷新控件
    self.tableView.header = header;
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.footer noticeNoMoreData];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [self.tableView setTableFooterView:v];
    
    msArray = [[NSMutableArray alloc] init];
    xhArray = [[NSMutableArray alloc] init];
    evaluationArray = [[NSMutableArray alloc] init];
    pageNum2 = 1;

}
- (void)loadNewData
{
    [self.tableView reloadData];
    [self.delegate returnPage];
    [self.tableView.header endRefreshing];
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
    });
}


-(void)upDate
{
    [self.tableView.footer noticeNoMoreData];
    if (ccsInt == 0)
    {
        
    }
    else if (ccsInt == 1)
    {
        if ([[allArray allKeys] containsObject:@"ProductSpecifications"])
        {
            for (NSDictionary *pic in [allArray objectForKey:@"ProductSpecifications"])
            {
                [msArray addObject:pic];
            }
        }
    }
    else if (ccsInt == 2)
    {
        [self.tableView.footer endRefreshing];
        if (pageNum2 != 1)
        {
            [self.tableView reloadData];
            return;
        }
//        loading = [[LoadingView alloc] initWithFrame:self.view.frame];
//        [[UIApplication sharedApplication].keyWindow addSubview:loading];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSDictionary *myArray = [SendService ReviewsPage:productId pageNumber:pageNum2];
            dispatch_async(dispatch_get_main_queue(), ^{
//                NSLog(@"myArray %@",myArray);
//                [loading closeLoading];
                if (myArray != nil)
                {
                    if ([[[myArray objectForKey:@"Entity"] allKeys] containsObject:@"Items"])
                    {
                        for (NSDictionary *pic1 in [[myArray objectForKey:@"Entity"] objectForKey:@"Items"])
                        {
                            [evaluationArray addObject:pic1];
                        }
                    }
                    pageNum2 ++;

//                    NSLog(@"evaluationArray %@",evaluationArray);
                    [self.tableView reloadData];
                }

            });
        });
    }
    else if (ccsInt == 3)
    {
        if (xhArray.count > 0)
        {
            [self.tableView reloadData];
            return;
        }
//        loading = [[LoadingView alloc] initWithFrame:self.view.frame];
//        [[UIApplication sharedApplication].keyWindow addSubview:loading];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSDictionary *myArray = [SendService InterestingProducts];
            dispatch_async(dispatch_get_main_queue(), ^{
//              NSLog(@"myArray %@",myArray);
//                [loading closeLoading];
                if (myArray != nil)
                {
                    xhArray = [myArray objectForKey:@"Entity"];
//                    NSLog(@"xhArray  %@",xhArray);
                    [self.tableView reloadData];
                }
                
            });
        });
        
        
    }
    [self.tableView reloadData];

}

#pragma mark -
#pragma mark Table View DataSource

- (void)valueChanged:(id)sender
{
    CCSegmentedControl* segmentedControl1 = sender;
    ccsInt = (unsigned int)segmentedControl1.selectedSegmentIndex;
    [self upDate];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenMySize.size.width, 60)];
        myView.backgroundColor = [UIColor whiteColor];
        
        UIView *my2View = [[UIView alloc] initWithFrame:CGRectMake(0, 48, screenMySize.size.width, 12)];
        my2View.backgroundColor = bgColor;
        [myView addSubview:my2View];
        if (segmentedControl != nil) {
            [segmentedControl removeFromSuperview];
            segmentedControl = nil;
        }
        segmentedControl = [[CCSegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"概览",@"描述",@"评价",@"猜你喜欢", nil]];
        segmentedControl.frame = CGRectMake(0, 12, screenMySize.size.width, 36);
        segmentedControl.selectedStainView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"menu_press2.png"]];
        segmentedControl.selectedSegmentTextColor = [UIColor colorWithRed:252/255.0 green:177/255.0 blue:80/255.0 alpha:1];
        segmentedControl.segmentTextColor = [UIColor blackColor];
        segmentedControl.backgroundColor = [UIColor whiteColor];
        [segmentedControl addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
        segmentedControl.selectedSegmentIndex = ccsInt;
        [myView addSubview:segmentedControl];
        
        return myView;
    }
    return nil;
}

-(void)setType:(int)type
{
    ccsInt = type;
    segmentedControl.selectedSegmentIndex = ccsInt;
    [self upDate];;
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (ccsInt == 1)
    {
        return 2+msArray.count;
    }
    else if (ccsInt == 0)
    {
        return 1;
    }
    else if (ccsInt == 2)
    {
        return evaluationArray.count;
    }
    else if (ccsInt == 3) {
       return 1;
    }
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (ccsInt == 1)
    {
        return [self ccsInt:indexPath.row];
    }
    else if (ccsInt == 0) {
        return webHight;
    }
    else if (ccsInt == 2)
    {
        return [self twoHight:indexPath.row];
    }
    else if (ccsInt == 3) {
        return xhArray.count*viewFrame.size.height/4+10;
    }
    return YES;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:MJTableViewCellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MJTableViewCellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        aTableView.showsVerticalScrollIndicator = NO;
    }
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    return [self mCell:cell bCTableView:aTableView cellForRowAtIndexPath:indexPath];
    return cell;
}

- (UITableViewCell *)mCell:(UITableViewCell*)cell bCTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (ccsInt == 1)
    {
        NSString *name = nil;
        NSString *nameS = nil;
        
        
        if (indexPath.row == 0)
        {
            name = @"商品名称";
            nameS =[NSString stringWithFormat:@"%@",[allArray objectForKey:@"Name"]];
        }
        else if (indexPath.row == 1)
        {
            name = @"商品编号";
            nameS =[NSString stringWithFormat:@"%@",productId];
        }
        else
        {
            name = [NSString stringWithFormat:@"%@",[[msArray objectAtIndex:indexPath.row-2] objectForKey:@"SpecificationAttributeName"]];
            nameS = [NSString stringWithFormat:@"%@",[[msArray objectAtIndex:indexPath.row-2] objectForKey:@"ValueRaw"]];;
            nameS = [nameS stringByReplacingOccurrencesOfString:@"&#39;" withString:@"'"];
        }
        
        int tyHight = [SendService setString:nameS setSize:labelSize-2 setHight:screenMySize.size.width-100];

        if (tyHight < 30) {
            tyHight = 30;
        }
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(100,0, .5, tyHight)];
        bgView.backgroundColor = [UIColor colorWithWhite:.8 alpha:1];
        [cell.contentView addSubview:bgView];

        [cell.contentView addSubview:[self setFrame:CGRectMake(10, 5, 90, tyHight-5) setTitle:name setFont:labelSize-2 setColor:[UIColor blackColor]]];
        
        [cell.contentView addSubview:[self setFrame:CGRectMake(101, 5, screenMySize.size.width-100, tyHight-5) setTitle:nameS setFont:labelSize-2 setColor:[UIColor blackColor]]];
    }
    else if (ccsInt == 0)
    {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, screenMySize.size.width, webHight)];
        webView.backgroundColor = [UIColor whiteColor];
        webView.scalesPageToFit =NO;
        webView.opaque = NO;
        webView.delegate = self;
        webView.scrollView.scrollEnabled = NO;
        webView.dataDetectorTypes = UIDataDetectorTypeNone;
        [cell.contentView addSubview:webView];
        
        NSString *webviewText = [SendService webString];
        NSString *htmlString = [webviewText stringByAppendingFormat:@"%@",[allArray objectForKey:@"FullDescription"]];
        
        [webView loadHTMLString:htmlString baseURL:nil];
    }
    else if (ccsInt == 2)
    {
        NSDictionary *dic = [evaluationArray objectAtIndex:indexPath.row];
        int hight = [self twoHight:indexPath.row];
        
        [cell.contentView addSubview:[self setFrame:CGRectMake(10, 5, screenMySize.size.width-120, 20) setTitle:[dic objectForKey:@"CustomerName"] setFont:labelSize-2 setColor:[UIColor blackColor]]];
        
        [cell.contentView addSubview:[self setFrame:CGRectMake(screenMySize.size.width-110, 5, 100, 20) setTitle:[dic objectForKey:@"WrittenOnStr"] setFont:labelSize-2 setColor:[UIColor blackColor]]];
        
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(20,25 -.5, screenMySize.size.width-40, .5)];
        bgView.backgroundColor = [UIColor colorWithWhite:.9 alpha:1];
        [cell.contentView addSubview:bgView];
        
        int tyHight = [SendService setString:[dic objectForKey:@"ReviewText"] setSize:labelSize setHight:screenMySize.size.width-20];
        if (tyHight< 20) {
            tyHight = 20;
        }
        
        [cell.contentView addSubview:[self setFrame:CGRectMake(10, 45, screenMySize.size.width-20, tyHight) setTitle:[dic objectForKey:@"ReviewText"] setFont:labelSize-2 setColor:[UIColor blackColor]]];
        
        NSMutableArray *picArray = [[NSMutableArray alloc] init];
        if ([[dic allKeys] containsObject:@"PicList"])
        {
            for (NSDictionary *pic in [dic objectForKey:@"PicList"])
                [picArray addObject:pic];
        }
        
        if (picArray.count > 0)
        {
            UIScrollView *ta1ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(10,45+tyHight, screenMySize.size.width-20, screenMySize.size.width/2)];
            ta1ScrollView.backgroundColor = [UIColor clearColor];
            [ta1ScrollView setShowsHorizontalScrollIndicator:NO];
            [cell.contentView addSubview:ta1ScrollView];
            
            [ta1ScrollView setContentSize:CGSizeMake(((screenMySize.size.width-30)/2+10)*picArray.count,screenMySize.size.width/2)];
            
            
            for (int i = 0; i < picArray.count; i ++)
            {
                NSMutableDictionary *dictionary = [picArray objectAtIndex:i];
                
                UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(((screenMySize.size.width-30)/2+10)*i,0, (screenMySize.size.width-30)/2, screenMySize.size.width/2)];
                [bgImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"Url_75"]]]];
                bgImageView.contentMode = UIViewContentModeScaleAspectFill;
                bgImageView.clipsToBounds  = YES;
                [ta1ScrollView addSubview:bgImageView];
                
                UIButton *inButton = [UIButton buttonWithType:UIButtonTypeCustom];
                CGRect frame = bgImageView.frame;
                [inButton setFrame:frame];
                inButton.tag = picTag*(indexPath.row+1)+i;
                [inButton addTarget:self action:@selector(aInAction:) forControlEvents:UIControlEventTouchUpInside];
                [ta1ScrollView addSubview:inButton];
            }
        }

        
        float typeF = [[NSString stringWithFormat:@"%@",[dic objectForKey:@"Rating"]] floatValue]*75/5;
        TQStarRatingView *starRatingView = [[TQStarRatingView alloc] initWithFrame:CGRectMake(10, 30, 75, 15) numberOfStar:5 initNum:typeF setBool:YES];
        [cell.contentView addSubview:starRatingView];
        UIView *tqsView = [[UIView alloc] initWithFrame:starRatingView.frame];
        tqsView.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:tqsView];
        
        
        NSString *mString = nil;
        if ([[dic allKeys] containsObject:@"AttributeList"])
        {
            for (NSDictionary *pic in [dic objectForKey:@"AttributeList"])
            {
                if (mString == nil) {
                    mString = [NSString stringWithFormat:@"%@:%@",[pic objectForKey:@"AttributeKey"],[pic objectForKey:@"AttributeValue"]];
                }
                else
                    mString = [NSString stringWithFormat:@"%@,%@:%@",mString,[pic objectForKey:@"AttributeKey"],[pic objectForKey:@"AttributeValue"]];

            }
        }
        [cell.contentView addSubview:[self setFrame:CGRectMake(10, hight-40, screenMySize.size.width-20, 20) setTitle:mString setFont:labelSize-2 setColor:[UIColor grayColor]]];
        
        [cell.contentView addSubview:[self setFrame:CGRectMake(10, hight-20, screenMySize.size.width-20, 20) setTitle:[NSString stringWithFormat:@"购买时间:%@",[dic objectForKey:@"CreatedOnUtc"]] setFont:labelSize-2 setColor:[UIColor grayColor]]];
        
    }
    else if (ccsInt == 3)
    {
        for (int i = 0; i < xhArray.count; i ++)
        {
            NSMutableDictionary *dictionary = [xhArray objectAtIndex:i];
            
            UIView *bgdView = [[UIView alloc] initWithFrame:CGRectMake(10,5+i*viewFrame.size.height/4, self.view.bounds.size.width-20, viewFrame.size.height/4-5)];
            bgdView.backgroundColor = [UIColor grayColor];
            bgdView.layer.cornerRadius = 5.0f;
            [cell.contentView addSubview:bgdView];
            
            UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(.5,.5, self.view.bounds.size.width-21, viewFrame.size.height/4-6)];
            bgView.backgroundColor = [UIColor whiteColor];
            bgView.layer.cornerRadius = 5.0f;
            [bgdView addSubview:bgView];
            
            UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(.5,.5, self.view.bounds.size.width/2-10, viewFrame.size.height/4-6)];
            [bgImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[[dictionary objectForKey:@"DefaultPictureModel" ] objectForKey:@"ImageUrl"]]]];
            bgImageView.clipsToBounds  = YES;
            bgImageView.backgroundColor = [UIColor grayColor];
            bgImageView.layer.cornerRadius = 5.0f;
            [bgdView addSubview:bgImageView];
            
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/2,5, self.view.bounds.size.width/2-20, viewFrame.size.height*3/16)];
            titleLabel.text = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"Name"]];
            titleLabel.textAlignment = 0;
            titleLabel.numberOfLines = 3;
            titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-2];
            titleLabel.textColor = [UIColor blackColor];
            [bgdView addSubview:titleLabel];
            
            UILabel *title1Label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/2,viewFrame.size.height*3/16, self.view.bounds.size.width/2-20, viewFrame.size.height/16-10)];
            title1Label.text = [NSString stringWithFormat:@"%@",[[dictionary objectForKey:@"ProductPrice"] objectForKey:@"Price"]];
            title1Label.textAlignment = 0;
            title1Label.font = [UIFont fontWithName:@"Arial" size:labelSize+1];
            title1Label.backgroundColor = [UIColor clearColor];
            title1Label.textColor = [UIColor redColor];
            [bgdView addSubview:title1Label];
            
            
            UIButton *inButton = [UIButton buttonWithType:UIButtonTypeCustom];
            CGRect frame = bgView.frame;
            [inButton setFrame:frame];
            inButton.tag = xhTag+i;
            [inButton addTarget:self action:@selector(cInfAction:) forControlEvents:UIControlEventTouchUpInside];
            [bgdView addSubview:inButton];
            
            
        }
    }
    return cell;
}

- (void)webViewDidFinishLoad:(UIWebView *)waebView
{
    if (webHight != 0) {
        return;
    }
    webHight = [[waebView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] floatValue];
    [self.tableView reloadData];
}

-(void)cInfAction:(id)sender
{
    int type = ((UIButton*)sender).tag-xhTag;
    if (xhArray.count<= type) {
        return;
    }
    NSMutableDictionary *dictionary = [xhArray objectAtIndex:type];
    [self setNSMutableDictionary:dictionary];
}

#pragma mark 详情界面跳转
-(void)setNSMutableDictionary:(NSMutableDictionary*)dictionary
{
    GoodsDetailsViewController *details = [[GoodsDetailsViewController alloc] init];
    details.productId = [NSString stringWithFormat:@"%@",[[dictionary objectForKey:@"ReviewOverviewModel"] objectForKey:@"ProductId"]];
    details.hidesBottomBarWhenPushed = YES;
    [self.delegate setController:details];
}

-(int)ccsInt:(int)type
{
    int tyHight = 0;
    NSString *nameS = nil;
    if (type == 0)
    {
        nameS =[NSString stringWithFormat:@"%@",[allArray objectForKey:@"Name"]];
    }
    else if (type == 1)
    {
        nameS =[NSString stringWithFormat:@"%@",productId];
    }
    else
    {
        nameS = [NSString stringWithFormat:@"%@",[[msArray objectAtIndex:type-2] objectForKey:@"ValueRaw"]];;
        nameS = [nameS stringByReplacingOccurrencesOfString:@"&#39;" withString:@"'"];
    }
    tyHight = [SendService setString:nameS setSize:labelSize-2 setHight:screenMySize.size.width-100];
    
    if (tyHight < 30) {
        tyHight = 30;
    }
    return tyHight;
}


-(UILabel*)setFrame:(CGRect)frame setTitle:(NSString*)title setFont:(int)font setColor:(UIColor*)myColor
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
    if (title != nil)
        titleLabel.text = [NSString stringWithFormat:@"%@",title];
    titleLabel.textAlignment = 0;
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont fontWithName:@"Arial" size:font];
    titleLabel.textColor = myColor;
    return titleLabel;
}



-(int)twoHight:(int)type
{
    int Higet = 80;
    
    NSDictionary *dicr = [evaluationArray objectAtIndex:type];
    
    if ([[dicr allKeys] containsObject:@"PicList"])
    {
        for (NSDictionary *pic1 in [dicr objectForKey:@"PicList"])
        {
            if ([[pic1 allKeys] containsObject:@"Url"])
            {
                Higet = Higet + screenMySize.size.width/2;
                break;
            }
        }
    }
    int tyHight = [SendService setString:[dicr objectForKey:@"ReviewText"] setSize:labelSize setHight:screenMySize.size.width-20];
    if (tyHight< 20) {
        tyHight = 20;
    }
    return Higet+tyHight;
}

-(void)aInAction:(id)sender
{
    int  type = ((UIButton*)sender).tag;
    int  iInt = type%picTag;
    int  index = type/picTag -1;
    
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    NSMutableArray *thumbs = [[NSMutableArray alloc] init];
    MWPhoto *photo;
    BOOL enableGrid = YES;
    BOOL startOnGrid = NO;
    
    NSDictionary *dicr = [evaluationArray objectAtIndex:index];
    if ([[dicr allKeys] containsObject:@"PicList"])
    {
        for (NSDictionary *pic1 in [dicr objectForKey:@"PicList"])
        {
            if ([[pic1 allKeys] containsObject:@"Url"])
            {
                photo = [MWPhoto photoWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[pic1 objectForKey:@"Url"]]]];
                [thumbs addObject:photo];
                photo.caption =nil;
                [photos addObject:photo];
            }
        }
    }
    
    self._photos = photos;
    self._thumbs = thumbs;
    // Create browser
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;//分享按钮,默认是
    browser.displayNavArrows = YES;//左右分页切换,默认否
    browser.displaySelectionButtons = NO;//是否显示选择按钮在图片上,默认否
    browser.alwaysShowControls = NO;//控制条件控件 是否显示,默认否
    browser.zoomPhotosToFill = YES;//是否全屏,默认是
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
    browser.wantsFullScreenLayout = YES;
#endif
    browser.enableGrid = enableGrid;
    browser.startOnGrid = startOnGrid;
    browser.enableSwipeToDismiss = YES;
    [browser setCurrentPhotoIndex:iInt];
    
    // Reset selections
    if (photos.count>0) {
        _selections = [NSMutableArray new];
        for (int i = 0; i < photos.count; i++) {
            [_selections addObject:[NSNumber numberWithBool:NO]];
        }
    }
    //    [self presentViewController:browser animated:YES completion:nil];
    [self.delegate setController:browser];
    //    [self.navigationController pushViewController:browser animated:YES];
    
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
    NSURL *requestURL =[request URL];
    if ( ( [ [ requestURL scheme ] isEqualToString: @"http" ] || [ [ requestURL scheme ] isEqualToString: @"https" ] || [ [ requestURL scheme ] isEqualToString: @"mailto" ])
        && ( navigationType == UIWebViewNavigationTypeLinkClicked ) ) {
        return ![ [ UIApplication sharedApplication ] openURL: requestURL];
    }
    
    return YES;
}

#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    if (index < _thumbs.count)
        return [_thumbs objectAtIndex:index];
    return nil;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
    //    NSLog(@"Did start viewing photo at index %lu", (unsigned long)index);
}

- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
    return [[_selections objectAtIndex:index] boolValue];
}

//- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index {
//    return [NSString stringWithFormat:@"Photo %lu", (unsigned long)index+1];
//}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
    [_selections replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:selected]];
    //    NSLog(@"Photo at index %lu selected %@", (unsigned long)index, selected ? @"YES" : @"NO");
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
    // If we subscribe to this method we must dismiss the view controller ourselves
    //    NSLog(@"Did finish modal presentation");
    [self dismissViewControllerAnimated:YES completion:nil];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
